﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;

namespace ExcelAddIn1
{
    /**
     * This class holds all datasets read from an Excel spreadsheet.
     */
    class DataContainer
    {
        //List of datasets.
        private List<DataSet> sets;

        /**
         * Creates a new dataset container.
         */
        public DataContainer()
        {
            sets = new List<DataSet>();
        }

        /**
         * Adds a new dataset (column).
         */
        public void AddSet(String name)
        {
            sets.Add(new DataSet(name));
        }

        /**
         * Adds a datapoint to a specific dataset.
         */
        public void AddValue(int index, double value)
        {
            DataSet d = sets[index];
            d.AddValue(value);
        }

        /**
         * Returns the number of datasets, usually known as the k number.
         */
        public int GetNoSets()
        {
            return sets.Count;
        }

        /**
         * Returns a specific dataset. 0 for the first dataset, 1 for the second etc.
         */
        public DataSet GetDataSet(int index)
        {
            return sets[index];
        }

        /**
         * Reads all selected datasets (columns) from the active Excel
         * spreadsheet.
         */
        public void CreateFromExcel(Excel.Range selection)
        {
            int rows = selection.Rows.Count;
            int cols = selection.Columns.Count;

            for (int c = 1; c <= cols; c++)
            {
                //See if we have a header on row 1
                Excel.Range cell = selection.get_Item(1, c) as Excel.Range;
                try
                {
                    double v = Convert.ToDouble(cell.Value2);
                    //No header found. Add a generic header.
                    AddSet("Serie " + c);
                }
                catch (Exception)
                {
                    //Header found. Use it!
                    AddSet(cell.Value2.ToString());
                }

                //Add the data
                for (int r = 1; r <= rows; r++)
                {
                    try
                    {
                        cell = selection.get_Item(r, c) as Excel.Range;
                        if (!cell.Value2.ToString().Equals(""))
                        {
                            double v = Convert.ToDouble(cell.Value2);
                            AddValue(c - 1, v);
                        }
                    }
                    catch (Exception)
                    {
                        //No number. Do nothing
                    }
                }
            }
        }
    }
}
